<template>
  <view class="detail-container">
    <!-- 导航栏 -->
    <uni-nav-bar 
      :title="pageTitle" 
      left-icon="back" 
      :right-text="isEditMode ? '保存' : '编辑'"
      @clickLeft="handleBack"
      @clickRight="handleRightAction"
      :loading="loading"
    />

    <!-- 内容区域 -->
    <scroll-view class="content-scroll" scroll-y>
      <!-- 查看模式 -->
      <view v-if="!isEditMode" class="view-mode">
        <!-- 活动图片 -->
        <view class="image-section" v-if="activityDetail.image">
          <image 
            class="activity-image" 
            :src="activityDetail.image" 
            mode="aspectFill"
            @click="previewImage"
          />
        </view>

        <!-- 基本信息 -->
        <view class="info-card">
          <view class="card-header">
            <text class="activity-name">{{ activityDetail.name }}</text>
            <uni-tag 
              :text="getStatusText(activityDetail)" 
              :type="getStatusType(activityDetail)"
              size="small"
            />
          </view>
          <text class="activity-desc">{{ activityDetail.description }}</text>
          
          <view class="price-section">
            <view class="price-item">
              <text class="price-label">原价</text>
              <text class="original-price">¥{{ formatPrice(activityDetail.original_price) }}</text>
            </view>
            <view class="price-item">
              <text class="price-label">团购价</text>
              <text class="group-price">¥{{ formatPrice(activityDetail.group_price) }}</text>
            </view>
          </view>
        </view>

        <!-- 活动详情 -->
        <view class="detail-card">
          <view class="card-title">活动详情</view>
          <view class="detail-item">
            <uni-icons type="person" size="16" color="#666" />
            <text class="detail-label">成团人数</text>
            <text class="detail-value">{{ activityDetail.min_members }}{{ activityDetail.max_members ? `-${activityDetail.max_members}` : '' }}人</text>
          </view>
          <view class="detail-item">
            <uni-icons type="clock" size="16" color="#666" />
            <text class="detail-label">可抵扣时长</text>
            <text class="detail-value">{{ activityDetail.deductible_hours }}小时</text>
          </view>
          <view class="detail-item">
            <uni-icons type="calendar" size="16" color="#666" />
            <text class="detail-label">活动时间</text>
            <text class="detail-value">{{ formatTimeRange(activityDetail.start_time, activityDetail.end_time) }}</text>
          </view>
          <view class="detail-item" v-if="activityDetail.limit_per_member > 0">
            <uni-icons type="shop" size="16" color="#666" />
            <text class="detail-label">每人限购</text>
            <text class="detail-value">{{ activityDetail.limit_per_member }}件</text>
          </view>
        </view>

        <!-- 适用范围 -->
        <view class="scope-card" v-if="storeNames.length > 0 || venueNames.length > 0">
          <view class="card-title">适用范围</view>
          <view class="scope-item" v-if="storeNames.length > 0">
            <text class="scope-label">适用门店</text>
            <view class="scope-tags">
              <uni-tag 
                v-for="store in storeNames" 
                :key="store" 
                :text="store" 
                type="primary" 
                size="small"
              />
            </view>
          </view>
          <view class="scope-item" v-if="venueNames.length > 0">
            <text class="scope-label">适用场地</text>
            <view class="scope-tags">
              <uni-tag 
                v-for="venue in venueNames" 
                :key="venue" 
                :text="venue" 
                type="success" 
                size="small"
              />
            </view>
          </view>
        </view>

        <!-- 可用时间 -->
        <view class="time-card" v-if="activityDetail.available_weekdays?.length > 0 || activityDetail.available_times?.length > 0">
          <view class="card-title">可用时间</view>
          <view class="time-item" v-if="activityDetail.available_weekdays?.length > 0">
            <text class="time-label">可用星期</text>
            <view class="weekday-tags">
              <uni-tag 
                v-for="day in activityDetail.available_weekdays" 
                :key="day" 
                :text="getWeekdayText(day)" 
                type="warning" 
                size="small"
              />
            </view>
          </view>
          <view class="time-item" v-if="activityDetail.available_times?.length > 0">
            <text class="time-label">可用时段</text>
            <view class="time-slots">
              <view 
                v-for="(time, index) in activityDetail.available_times" 
                :key="index"
                class="time-slot"
              >
                <text>{{ time.start_time }} - {{ time.end_time }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 编辑模式 -->
      <view v-else class="edit-mode">
        <ActivityForm 
          :initial-values="activityDetail"
          @submit="handleSubmit"
          @cancel="handleCancel"
          :loading="loading"
        />
      </view>
    </scroll-view>

    <!-- 底部操作栏 (仅查看模式显示) -->
    <view v-if="!isEditMode" class="bottom-actions">
      <button class="action-btn secondary" @click="handleEdit">
        <uni-icons type="compose" size="18" />
        <text>编辑</text>
      </button>
      <button class="action-btn danger" @click="handleDelete">
        <uni-icons type="trash" size="18" />
        <text>删除</text>
      </button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { onLoad, onShow } from '@dcloudio/uni-app';
import { activityApi, commonApi } from '@/api/groupbuy';
import type { Activity } from '@/types/groupbuy';
import ActivityForm from './components/ActivityForm.vue';

// 页面参数
interface PageParams {
  id?: string;
  mode?: 'view' | 'edit' | 'create';
}

// 响应式数据
const loading = ref(false);
const activityDetail = ref<Activity>({} as Activity);
const isEditMode = ref(false);
const pageMode = ref<'view' | 'edit' | 'create'>('view');
const activityId = ref<number>(0);
const storeList = ref<any[]>([]);
const venueList = ref<any[]>([]);

// 计算属性
const pageTitle = computed(() => {
  if (pageMode.value === 'create') return '创建活动';
  if (isEditMode.value) return '编辑活动';
  return '活动详情';
});

const storeNames = computed(() => {
  if (!activityDetail.value.applicable_stores?.length) return [];
  return activityDetail.value.applicable_stores.map(storeId => {
    const store = storeList.value.find(s => s.id === storeId);
    return store?.name || '';
  }).filter(Boolean);
});

const venueNames = computed(() => {
  if (!activityDetail.value.applicable_venues?.length) return [];
  return activityDetail.value.applicable_venues.map(venueId => {
    const venue = venueList.value.find(v => v.id === venueId);
    return venue?.name || '';
  }).filter(Boolean);
});

// 页面加载
onLoad((options: any) => {
  const { id, mode = 'view' } = options as PageParams;
  pageMode.value = mode;
  
  if (mode === 'create') {
    isEditMode.value = true;
    activityDetail.value = getDefaultActivity();
  } else if (id) {
    activityId.value = parseInt(id);
    isEditMode.value = mode === 'edit';
  }
});

onShow(() => {
  if (activityId.value) {
    loadActivityDetail();
  }
  loadStoreList();
});

// 获取默认活动数据
const getDefaultActivity = (): Activity => {
  const now = Math.floor(Date.now() / 1000);
  return {
    id: 0,
    name: '',
    description: '',
    image: '',
    original_price: 0,
    group_price: 0,
    start_time: now,
    end_time: now + 7 * 24 * 3600, // 7天后
    min_members: 2,
    max_members: 0,
    limit_per_member: 1,
    support_balance: false,
    deductible_hours: 1,
    applicable_stores: [],
    applicable_venues: [],
    available_weekdays: [],
    available_times: [],
    sort_order: 0,
    status: 1,
  };
};

// 加载活动详情
const loadActivityDetail = async () => {
  try {
    loading.value = true;
    const res = await activityApi.getDetail(activityId.value);
    if (res) {
      activityDetail.value = res;
    }
  } catch (error) {
    console.error('加载活动详情失败:', error);
    uni.showToast({
      title: '加载失败',
      icon: 'none',
    });
  } finally {
    loading.value = false;
  }
};

// 加载门店列表
const loadStoreList = async () => {
  try {
    const res = await commonApi.getStores();
    if (res?.list) {
      storeList.value = res.list;
      // 加载所有场地
      loadAllVenues();
    }
  } catch (error) {
    console.error('加载门店列表失败:', error);
  }
};

// 加载所有场地
const loadAllVenues = async () => {
  try {
    const res = await commonApi.getVenues();
    if (res?.list) {
      venueList.value = res.list;
    }
  } catch (error) {
    console.error('加载场地列表失败:', error);
  }
};

// 格式化价格
const formatPrice = (price: number) => {
  return (price / 100).toFixed(2);
};

// 格式化时间范围
const formatTimeRange = (startTime: number, endTime: number) => {
  const start = new Date(startTime * 1000);
  const end = new Date(endTime * 1000);
  const formatDate = (date: Date) => {
    return `${date.getMonth() + 1}/${date.getDate()} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
  };
  return `${formatDate(start)} - ${formatDate(end)}`;
};

// 获取状态文本
const getStatusText = (activity: Activity) => {
  const now = Date.now() / 1000;
  if (activity.status === 0) return '已禁用';
  if (now < activity.start_time) return '未开始';
  if (now > activity.end_time) return '已结束';
  return '进行中';
};

// 获取状态类型
const getStatusType = (activity: Activity) => {
  const now = Date.now() / 1000;
  if (activity.status === 0) return 'error';
  if (now < activity.start_time) return 'warning';
  if (now > activity.end_time) return 'info';
  return 'success';
};

// 获取星期文本
const getWeekdayText = (day: number) => {
  const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
  return weekdays[day] || '';
};

// 预览图片
const previewImage = () => {
  if (activityDetail.value.image) {
    uni.previewImage({
      urls: [activityDetail.value.image],
    });
  }
};

// 处理返回
const handleBack = () => {
  if (isEditMode.value && pageMode.value !== 'create') {
    // 编辑模式下返回查看模式
    isEditMode.value = false;
  } else {
    // 返回上一页
    uni.navigateBack();
  }
};

// 处理右侧操作
const handleRightAction = () => {
  if (isEditMode.value) {
    // 保存操作由表单组件处理
    return;
  } else {
    // 进入编辑模式
    handleEdit();
  }
};

// 处理编辑
const handleEdit = () => {
  isEditMode.value = true;
};

// 处理取消编辑
const handleCancel = () => {
  if (pageMode.value === 'create') {
    uni.navigateBack();
  } else {
    isEditMode.value = false;
  }
};

// 处理表单提交
const handleSubmit = async (formData: Activity) => {
  try {
    loading.value = true;
    
    if (pageMode.value === 'create') {
      await activityApi.create(formData);
      uni.showToast({
        title: '创建成功',
        icon: 'success',
      });
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    } else {
      await activityApi.update(activityId.value, formData);
      uni.showToast({
        title: '更新成功',
        icon: 'success',
      });
      isEditMode.value = false;
      loadActivityDetail();
    }
  } catch (error) {
    console.error('保存失败:', error);
    uni.showToast({
      title: '保存失败',
      icon: 'none',
    });
  } finally {
    loading.value = false;
  }
};

// 处理删除
const handleDelete = () => {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除这个团购活动吗？删除后无法恢复。',
        success: async (result: any) => {
          if (result.confirm) {
            try {
              loading.value = true;
              await activityApi.delete(activityId.value);
              uni.showToast({
                title: '删除成功',
                icon: 'success',
              });
              setTimeout(() => {
                uni.navigateBack();
              }, 1500);
            } catch (error) {
              console.error('删除失败:', error);
              uni.showToast({
                title: '删除失败',
                icon: 'none',
              });
            } finally {
              loading.value = false;
            }
          }
        },
  });
};
</script>

<style lang="scss" scoped>
.detail-container {
  height: 100vh;
  background: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.content-scroll {
  flex: 1;
  padding: 24rpx;
}

.image-section {
  margin-bottom: 24rpx;
  
  .activity-image {
    width: 100%;
    height: 400rpx;
    border-radius: 16rpx;
  }
}

.info-card, .detail-card, .scope-card, .time-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 32rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16rpx;
  
  .activity-name {
    flex: 1;
    font-size: 36rpx;
    font-weight: 600;
    color: #333;
    margin-right: 16rpx;
  }
}

.activity-desc {
  font-size: 28rpx;
  color: #666;
  line-height: 1.6;
  margin-bottom: 24rpx;
}

.price-section {
  display: flex;
  gap: 32rpx;
  
  .price-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    
    .price-label {
      font-size: 24rpx;
      color: #999;
      margin-bottom: 8rpx;
    }
    
    .original-price {
      font-size: 28rpx;
      color: #999;
      text-decoration: line-through;
    }
    
    .group-price {
      font-size: 32rpx;
      font-weight: 600;
      color: #FF4D4F;
    }
  }
}

.card-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 24rpx;
}

.detail-item {
  display: flex;
  align-items: center;
  margin-bottom: 16rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
  
  .detail-label {
    font-size: 28rpx;
    color: #666;
    margin: 0 16rpx 0 12rpx;
    min-width: 120rpx;
  }
  
  .detail-value {
    font-size: 28rpx;
    color: #333;
    flex: 1;
  }
}

.scope-item, .time-item {
  margin-bottom: 24rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
  
  .scope-label, .time-label {
    font-size: 28rpx;
    color: #666;
    margin-bottom: 12rpx;
    display: block;
  }
}

.scope-tags, .weekday-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 12rpx;
}

.time-slots {
  .time-slot {
    background: #f5f5f5;
    padding: 12rpx 16rpx;
    border-radius: 8rpx;
    margin-bottom: 8rpx;
    
    text {
      font-size: 26rpx;
      color: #666;
    }
  }
}

.bottom-actions {
  display: flex;
  padding: 24rpx 32rpx;
  background: #fff;
  border-top: 1rpx solid #f0f0f0;
  gap: 24rpx;
  
  .action-btn {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8rpx;
    padding: 24rpx;
    border-radius: 12rpx;
    font-size: 28rpx;
    border: none;
    
    &.secondary {
      background: #f5f5f5;
      color: #666;
    }
    
    &.danger {
      background: #FF4D4F;
      color: #fff;
    }
    
    &:active {
      opacity: 0.8;
    }
  }
}

.edit-mode {
  background: #fff;
  border-radius: 16rpx;
  padding: 32rpx;
}
</style>